from rest_framework import serializers
from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation import validate_password
from .models import MembershipType, LoginLog

User = get_user_model()

class UserRegisterSerializer(serializers.ModelSerializer):
    """用户注册序列化器"""
    password = serializers.CharField(write_only=True, required=True, validators=[validate_password])
    password_confirm = serializers.CharField(write_only=True, required=False)

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'first_name', 'last_name', 'phone', 'password', 'password_confirm')
        extra_kwargs = {
            'email': {'required': True},
            'username': {'required': True}
        }

    def validate(self, attrs):
        password = attrs.get('password')
        password_confirm = attrs.get('password_confirm')
        
        # 如果提供了确认密码，则验证两次密码是否一致
        if password_confirm and password != password_confirm:
            raise serializers.ValidationError({"password": "两次密码不匹配"})
        return attrs

    def create(self, validated_data):
        validated_data.pop('password_confirm', None)
        user = User.objects.create_user(**validated_data)
        return user


class UserLoginSerializer(serializers.Serializer):
    """用户登录序列化器"""
    username = serializers.CharField(required=False)
    email = serializers.EmailField(required=False)
    phone = serializers.CharField(required=False)
    password = serializers.CharField(required=True, write_only=True)

    def validate(self, attrs):
        username = attrs.get('username')
        email = attrs.get('email')
        phone = attrs.get('phone')
        
        if not any([username, email, phone]):
            raise serializers.ValidationError("请提供用户名、邮箱或手机号")
        
        return attrs


class UserSerializer(serializers.ModelSerializer):
    """用户信息序列化器"""
    membership_name = serializers.SerializerMethodField()
    prompt_limit = serializers.SerializerMethodField()
    
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'phone', 'avatar', 'prompt_count', 
                  'prompt_limit', 'membership', 'membership_name', 'is_active', 
                  'date_joined', 'last_login')
        read_only_fields = ('prompt_count', 'prompt_limit', 'membership', 
                           'membership_name', 'date_joined', 'last_login')
    
    def get_membership_name(self, obj):
        if obj.membership:
            return obj.membership.name
        return "免费会员"
    
    def get_prompt_limit(self, obj):
        if obj.membership:
            return obj.membership.prompt_limit
        return 0


class MembershipTypeSerializer(serializers.ModelSerializer):
    """会员类型序列化器"""
    class Meta:
        model = MembershipType
        fields = ('id', 'name', 'prompt_limit', 'description', 'is_default')


class LoginLogSerializer(serializers.ModelSerializer):
    """登录日志序列化器"""
    class Meta:
        model = LoginLog
        fields = ('id', 'user', 'ip_address', 'login_time', 'is_success', 'user_agent')
        read_only_fields = ('id', 'user', 'ip_address', 'login_time', 'is_success', 'user_agent')


class ChangePasswordSerializer(serializers.Serializer):
    """修改密码序列化器"""
    old_password = serializers.CharField(required=True)
    new_password = serializers.CharField(required=True, validators=[validate_password])
    new_password_confirm = serializers.CharField(required=True)

    def validate(self, attrs):
        if attrs['new_password'] != attrs['new_password_confirm']:
            raise serializers.ValidationError({"new_password": "两次密码不匹配"})
        return attrs